import { memo, MouseEvent } from 'react'
import styles from './index.module.scss'
import classNames from 'classnames'
// import QuestionTitle from '@/components/Question/QuestionTitle/Component'
// import QuestionInput from '@/components/Question/QuestionInput/Component'
import { Spin } from 'antd'
import useGetComponentInfo from '@/hooks/useGetComponentInfo'
import { getComponentConfByType } from '@/components/Question'
import {
  changeSelectedId,
  ComponentInfoType,
  moveComponent,
} from '@/store/features/componentsReducer'
import { useDispatch } from 'react-redux'
import useBindCanvasKeyPress from '@/hooks/useBindCanvasKeyPress'
import SortableContainer from '@/components/SortableContainer'
import SortableItem from '@/components/SortableContainer/SortableItem'

type PropsType = {
  loading: boolean
}

function genComponent(componentInfo: ComponentInfoType) {
  const { type, props } = componentInfo //每个组件的信息,是从  redux store 获取的(服务端获取)
  const componentConf = getComponentConfByType(type)

  if (componentConf == null) return null

  const { Component } = componentConf
  return <Component {...props} />
}
const EditCanvas = memo((props: PropsType) => {
  useBindCanvasKeyPress()
  const { loading } = props
  const { componentList, selectedId } = useGetComponentInfo()
  const dispatch = useDispatch()

  if (loading) {
    return (
      <div style={{ textAlign: 'center', marginTop: '24px' }}>
        <Spin />
      </div>
    )
  }

  //选中某个组件
  const handleChangeSelectedId = (event: MouseEvent, id: string) => {
    event.stopPropagation() //阻止冒泡
    dispatch(changeSelectedId(id))
  }

  // SortableContainer组件中的items属性 ,需要每个item都有id
  const componentListWidthId = componentList.map(c => ({ ...c, id: c.fe_id }))

  //拖拽排序结束
  function handleDragEnd(oldIndex: number, newIndex: number) {
    dispatch(moveComponent({ oldIndex, newIndex }))
  }

  return (
    <SortableContainer items={componentListWidthId} onDragEnd={handleDragEnd}>
      <div className={styles.canvas}>
        {componentList
          .filter(c => !c.isHidden)
          .map(c => {
            const { fe_id } = c
            const defaultClassName = styles['component-wrapper']
            const selectedClassName = styles.selected
            const lockedClassName = styles.locked
            const wrapperClassName = classNames({
              [defaultClassName]: true,
              [selectedClassName]: c.fe_id === selectedId,
              [lockedClassName]: c.isLocked,
            })
            return (
              <SortableItem key={fe_id} id={fe_id}>
                <div
                  key={c.fe_id}
                  className={wrapperClassName}
                  onClick={e => handleChangeSelectedId(e, c.fe_id)}
                >
                  <div className={styles.component}>{genComponent(c)}</div>
                </div>
              </SortableItem>
            )
          })}
      </div>
    </SortableContainer>
  )
})

export default EditCanvas
